Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

136
Visualizações
How to add "Bearer" another route headers after user logged in?

I'm new to programming and I'm currently working on a small project.

I'm trying to implement some authorization using JWT. I've watched a few videos online and found that most people have the "Bearer" + access token in their headers.

I've gone through a few posts and I found that I needed to add the authorization "Bearer" myself but I'm not quite sure how to get there.

Can I please get some help?

Here are some of my code

Login

 if(response){
            if(await bcrypt.compare(loginPW, response.password)){
                const accessToken = jwt.sign({
                    email: response.email
                },jwtSecret)
                res.json({status: 'ok', accessToken: accessToken})
            }else{
                return res.json({status: 'error', error:'Invalid Credentials'})
            }
        }

Post request

const result = await fetch('/',{
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            loginEmail, loginPassword, reqType
        })
    }).then((res) => res.json());
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

one possible way is ....on your Post requst result you can store the accessToken in localStorage

const result = await fetch('/',{
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            loginEmail, loginPassword, reqType
        })
    }).then((res) => res.json()).then(({accessToken})=>{
 
localStorage.setItem('accessToken', accessToken)

});

then retrieve it in all of your requests

const anotherRequst = await fetch('/anything',{
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${localStorage.getItem('accessToken')}`  // get it from localStorage
        },
        body: ... /// anything 
    }).then((res) => res.json());

that's the simplest way

... for more advanced techniques, try to use Axios

and you can simply set the default authorization header in all your requsts

axios.defaults.authorization = localStorage.getItem('accessToken')

then any request you make will have the accessToken in its header

Axios.post(....)
Axios.get(...)
....

about 4 years ago · Juan Pablo Isaza Relatório

0

You can add 'Authorization' headers within your request just like this

const result = await fetch('/',{
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${accessToken}`
    },
    body: JSON.stringify({
        loginEmail, loginPassword, reqType
    })
}).then((res) => res.json());

Or if you're dealing with a big project and you have to send the token with every request then you can use Axios which allows you to add common headers with every request using only one line

axios.defaults.headers.common['Authorization'] = `Bearer ${accessToken}`;

Docs: https://www.npmjs.com/package/axios

about 4 years ago · Juan Pablo Isaza Relatório

0

just add Authorization header with your token to request

const result = await fetch('/',{
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
            'Authorization': `Bearer ${accessToken}`
        },
        body: JSON.stringify({
            loginEmail, loginPassword, reqType
        })
    }).then((res) => res.json());
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda